package runner

/*
#ifdef _WIN32
	#include<Windows.h>
	#ifdef _WIN64
		#cgo CFLAGS: -I ../lua-5.3.5_WIN64/include -std=gnu99
   		#cgo LDFLAGS: -L ../lua-5.3.5_WIN64 -static -llua53
	#else
		#cgo CFLAGS: -I ../lua-5.3.5_WIN32/include -std=gnu99
		#cgo LDFLAGS: -L ../lua-5.3.5_WIN32 -static -llua53
	#endif
#else
	#cgo CFLAGS: -I ../lua-5.3.5_Linux/include -std=gnu99
	#cgo LDFLAGS: -L ../lua-5.3.5_Linux -static -llua53
#endif

#include <signal.h>
#include <stdlib.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

static const char *progname;

// Message handler used to run all chunks
static int msghandler (lua_State *L) {
	const char *msg = lua_tostring(L, 1);
	if (msg == NULL) {  // is error object not a string?
		if (luaL_callmeta(L, 1, "__tostring") &&  // does it have a metamethod
 			lua_type(L, -1) == LUA_TSTRING) { // that produces a string?
				return 1;  // that is the message
		} else {
			msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1));
		}
	}
	luaL_traceback(L, L, msg, 1);  // append a standard traceback
	return 1;  // return the traceback
}

// Prints an error message, adding the program name in front of it
// (if present)
static void l_message (const char *pname, const char *msg) {
	if (pname) lua_writestringerror("%s: ", pname);
	lua_writestringerror("%s\n", msg);
}

// Check whether 'status' is not OK and, if so, prints the error
// message on the top of the stack. It assumes that the error object
// is a string, as it was either generated by Lua or by 'msghandler'.
static int report (lua_State *L, int status) {
	if (status != LUA_OK) {
		const char *msg = lua_tostring(L, -1);
		l_message(progname, msg);
		lua_pop(L, 1);  // remove message
	}
	return status;
}

void run_binaryscript (const char *s, const int len, const char *pname) {
#ifdef _WIN32
	SetConsoleOutputCP(65001); // utf8 output support
#endif
	progname = pname;
	lua_State *L = luaL_newstate();
	if (L == NULL) {
		l_message(progname, "cannot create state: not enough memory");
	}
	luaL_openlibs(L);
	lua_pushcfunction(L, msghandler);
	int status = luaL_loadbuffer(L, s, len, s);
	if (status == LUA_OK) {
		status = lua_pcall(L, 0, LUA_MULTRET, 0);
	}
	report(L, status);
	lua_close(L);
}
*/
import "C"
import (
	"unsafe"
)

func CRunBinary(b []byte, name string) {
	len := C.int(len(b))
	data := *(*string)(unsafe.Pointer(&b))
	cdata := C.CString(data)
	pname := C.CString(name)
	defer C.free(unsafe.Pointer(cdata))
	defer C.free(unsafe.Pointer(pname))
	C.run_binaryscript(cdata, len, pname)
}
